import { EventTarget, log } from "cc";
import { SocketConnection } from "../network/socket/SocketConnection";
import { Handler } from "../components/Handler";
import { ReceiveChannelMessageEventEnum, ReceiveMessageEventEnum, SendChannelMessageEventEnum, SendMessageEventEnum } from "../network/socket/SocketProtocol";

export class SocketAgentMgr {
    private static _instance:SocketAgentMgr;
    private _socket:SocketConnection;//主服务器
    private _chatSocket:SocketConnection;//聊天服务器
    private _eventTarget:EventTarget = new EventTarget();
    public static get instance():SocketAgentMgr{
        if(this._instance==null){
            this._instance = new SocketAgentMgr();
        }
        return this._instance
    }
    /**发送聊天信息*/
    public sendChatTextMessage(msg: string):void{
        this._chatSocket.sendMessage(SendMessageEventEnum.Text, {text: msg})
    }
    /**发送聊天表情*/
    public sendChatEmoji(emoji: string):void{
        this._chatSocket.sendMessage(SendMessageEventEnum.Emoji, {emoji: emoji})
    }
    /**
     * 
     * @param soketID 1主服务器 2聊天服务
     * @param type 
     * @param callback 
     * @param thisArg 
     */
    public on(soketID:number,type:ReceiveChannelMessageEventEnum | ReceiveMessageEventEnum, callback:any,thisArg?: any, once?: boolean):void{
        this._eventTarget.on(this.getEventType(soketID,type),callback,thisArg,once);
    }
    /**移除服务器监听*/
    public off(soketID:number,type:ReceiveChannelMessageEventEnum | ReceiveMessageEventEnum, callback:any,thisArg?: any):void{
        this._eventTarget.off(this.getEventType(soketID,type),callback,thisArg);
    }
    public offAll(thisArg: any):void{
        this._eventTarget.removeAll(thisArg);
    }
    /**开始连接主socket*/
    public startSocket():void{
        if(this._socket==null)
        {
            this._socket = new SocketConnection(new Handler(this,this.addMessage),1)
        }
        this._socket.connect();
    }
    /**连接聊天服务器*/
    public startChatSocket():void{
        if(this._chatSocket==null)
        {
            this._chatSocket = new SocketConnection(new Handler(this,this.addMessage),2)
        }
        this._chatSocket.connect();
    }
    /**更新多人房间里的数据*/
    public updateMultipleData():void{
        this._socket.sendMessage(SendChannelMessageEventEnum.GetInitData);
    }
    /**
     * 
     * @param socketID 1主服务器 2聊天服务
     */
    public closeSocket(socketID:number):void{
        if(socketID==1)
        {
            if(this._socket)
            {
                this._socket.close();
            }
        }else{
            if(this._chatSocket)
            {
                this._chatSocket.close();
            }
        }
    }
    //给socket回调用
    private addMessage(data:Array<any>):void{
        this._eventTarget.emit(this.getEventType(data[0],data[1]),data[2]);
    }
    private getEventType(socketID:number,type:string):string{
        return "socketID"+socketID+type;
    }
}